package com.store.app.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.http.Stores;
import com.store.app.http.Submit;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

//注册新用户
public class MembersRegeditActivity extends BaseActivity implements View.OnClickListener, IOnHttpListener {
    private TextView tvTitle;
    private EditText old_account;
    private EditText et_input_code;
    private TextView bt_submit;
    private TextView tvSendCode;
    private CountDownTimer downtimer;//倒计时
    private String app_token;
    private String security_code;
    private String phone;
    private String error;
    private NetRequest netRequest;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
            super.handleMessage(msg);
            switch (msg.what) {
                //提交成功
                case 1:
                    showToast("注册成功,您的登录信息已经发到指定的手机上!", Toast.LENGTH_LONG);
                    finish();
                    break;
                //获取apptoken成功,验证会员类型
                case 3:
                    if (TextUtils.isEmpty(phone)) {
                        showToast("请输入手机号");
                        return;
                    }
                    //new TestGetCode(phone).start();
                    //获取短信验证码验证信息
                    netRequest.requestSendSmsCodeMess(1,app_token);
                    break;
                //短信校验成功通过，开始调用提交接口

                //重新开始倒计时验证码
                case 6:
                    downtimer.cancel();
                    downtimer.onFinish();
                    tvSendCode.setEnabled(true);
                    break;
                case 5:
                    String s=(String) msg.obj;
                    if(!TextUtils.isEmpty(s)&&s.equals("抱歉，此功能暂未开通")){
                       // showToast("抱歉，此功能暂未开通");
                    }else{
                    showToast(s);}
                    break;
                //短信校验不通过,提交失败
                case 7:
                    showToast("短信校验不通过,提交失败:"+error);
                    break;
                case 9:
                    showToast("请检查本地网络！");
                    break;
                case 10:
                    if (TextUtils.isEmpty(error)) {
                        showToast("获取短信失败");
                    } else {
                        showToast("获取短信失败:" + error);
                    }
                    break;
                case 11:
                    showToast("用户不存在");
                    break;
                case 12:
                    showToast("你已注册为每天惠会员");
                    downtimer.cancel();
                    downtimer.onFinish();
                    tvSendCode.setEnabled(true);
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_membersregedit);
        initView();
        initData();
    }

    private void initData() {
        downtimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tvSendCode.setText((millisUntilFinished / 1000) + "秒后重发");
            }

            @Override
            public void onFinish() {
                tvSendCode.setEnabled(true);
                tvSendCode.setText("获取验证码");
            }
        };
        app_token = MainActivity.app_token;
        security_code = MainActivity.security_code;
        netRequest = new NetRequest(this);
    }

    private void initView() {
        findViewById(R.id.public_ll_return).setOnClickListener(this);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("注册新用户");
        old_account = (EditText) findViewById(R.id.old_account);
        et_input_code = (EditText) findViewById(R.id.et_input_code);
        bt_submit = (TextView) findViewById(R.id.bt_submit);
        tvSendCode = (TextView) findViewById(R.id.tv_send_code);
        tvSendCode.setOnClickListener(this);
        bt_submit.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_submit:
                submit();
                break;
            case R.id.public_ll_return:
                finish();
                break;
            case R.id.tv_send_code:
                sendCode();
                break;
        }
    }

    private void sendCode() {
        phone = old_account.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(MembersRegeditActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Utils.matchPhone(phone)) {
            Toast.makeText(MembersRegeditActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        downtimer.start();
        tvSendCode.setEnabled(false);
        if (TextUtils.isEmpty(app_token) | TextUtils.isEmpty(security_code)) {
            new register().start();
        } else {
            new CheckPhone(phone).start();

        }
    }

    private void submit() {



        String account = old_account.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Utils.matchPhone(account)) {
            Toast.makeText(this, "手机号类型不正确", Toast.LENGTH_SHORT).show();
            return;
        }
        String code = et_input_code.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        new SubmitInfo(account,code).start();
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1){
            if(TextUtils.isEmpty(result)) {
                showToast("获取短信验证码失败，请稍后重试！");
            }else{
                //获取短信验证码
                netRequest.requestSendSmsCode(2,app_token,phone,result);
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
       if (requestId == 1||requestId == 2) {
            //获取短信验证码失败
           error = msg;
           handler.sendEmptyMessage(6);
           handler.sendEmptyMessage(10);
        }
    }


    /**
     * 获取apptoken
     */
    public class register extends Thread {

        public void run() {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("app_id", SettingData.app_id));
            params.add(new BasicNameValuePair("private_key", SettingData.private_key));
            JSONObject obj = Submit.submit(params, Stores.http + "/openapi/app/login");
            try {
                String result = obj.getString("rsp_code");
                if (result.equals("succ")) {
                    Log.v("zyl", "获取app_token成功");
                    JSONObject data = obj.getJSONObject("data");
                    app_token = data.getString("app_token");
                    security_code = data.getString("security_code");
                    MainActivity.app_token = app_token;
                    MainActivity.security_code = security_code;
                    handler.sendEmptyMessage(3);
                } else {
                    Log.v("zyl", "获取app_token失败");
                }
            } catch (Exception e) {
            }
        }
    }
    //验证会员类型
    public class CheckPhone extends Thread {
        private String account;

        public CheckPhone(String account) {
            this.account = account;
        }

        public void run() {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("app_token", app_token));
            params.add(new BasicNameValuePair("member_type_key", "consumer"));
            params.add(new BasicNameValuePair("mobile", account));

            String sign = Submit.genPackageSign(params);
            params.add(new BasicNameValuePair("sign", sign));
            JSONObject obj = Submit.submit(params, SettingData.http + "/openapi/user/valid_type_by_mobile");
            try {
                Log.i("mylog","yanzheng "+obj.toString());
                String result = obj.getString("rsp_code");
                if (result.equals("succ")) {
                    JSONObject jsonObject=new JSONObject( obj.getString("data"));
                    String s_uesr=jsonObject.getString("member_type");
                    if("exist".equals(s_uesr)){
                        handler.sendEmptyMessage(12);
                    }else{
                        //new TestGetCode(phone).start();
                        //获取短信验证码验证信息
                        netRequest.requestSendSmsCodeMess(1,app_token);
                    }
                } else {
                    handler.sendEmptyMessage(11);
                }
            } catch (Exception e) {
                e.printStackTrace();
                handler.sendEmptyMessage(9);
            }

        }
    }



    //提交
    public class SubmitInfo extends Thread {
        private String mobile;
        private String code;

        /**

         * @param mobile                  手机
         */
        public SubmitInfo( String mobile,String code) {
            this.mobile = mobile;
            this.code=code;
        }

        public void run() {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("mobile", mobile));
            params.add(new BasicNameValuePair("sms_code", code));
            params.add(new BasicNameValuePair("user_token", MainActivity.user_token));
            String sign = Submit.genPackageSignUser(params);
            params.add(new BasicNameValuePair("sign", sign));
            JSONObject obj = Submit.submit(params, SettingData.http + "/openapi/consumer/reg_by_store");
            try {

                String result = obj.getString("rsp_code");
                Log.i("mylog",result+"aa"+obj.toString());
                if (result.equals("succ")) {
                    Log.v("zyl", "注册成功");
                    handler.sendEmptyMessage(1);
                } else {
                    Message msg = Message.obtain();
                    msg.what = 5;
                    msg.obj = obj.getString("error_msg");
                    Log.v("zyl","注册失败:"+msg.obj);
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.v("zyl","注册接口网络不通");
                Log.v("zyl", "获取验证码网络不通");
                // TODO Auto-generated catch block
                handler.sendEmptyMessage(9);
            }

        }
    }



}
